<template>
  <block>
    <template v-if="loaded">
      <slot :data="datasource"></slot>
    </template>
  </block>
</template>

<script setup lang="ts">
import { onLoad, onUnload } from '@dcloudio/uni-app'

const props = defineProps<{
  loader: () => Promise<any>
  onload?: (data: any, query: any) => any
  lazy?: boolean
}>()

const emit = defineEmits<{
  (e: 'loaded', data: any): void
}>()

defineExpose({
  init,
})

/**
 * 小程序端不支持<Suspense> 需要手动判空处理
 * Vue3.3支持泛型组件，当前版本使用Vue3.2不支持，因此使用any
 */
const loaded = ref(false)
let datasource: any | undefined = void 0
async function init() {
  datasource = await props.loader()
  loaded.value = true
  emit('loaded', datasource)
}
!props.lazy && init()

const onLoadTriggered = ref(false)
let onLoadQuery: any = {}

onLoad((query: any) => {
  onLoadTriggered.value = true
  onLoadQuery = query
})
onUnload(() => {
  onLoadTriggered.value = false
  onLoadQuery = {}
})

watchEffect(() => {
  if (loaded.value && onLoadTriggered.value && typeof props.onload === 'function') {
    nextTick(() => {
      props.onload?.(datasource, onLoadQuery)
    })
  }
})
</script>
